package cn.gdk.gaodekecc.exception;

import cn.gdk.gaodekecc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(Exception.class)
    public JSONResult handlerException(Exception e){
        e.printStackTrace();
        return JSONResult.error(GlobalExceptionCodeEunm.SERVICE_ERROR);
    }
    @ExceptionHandler(GlobalCommonException.class)
    public JSONResult globalCommonException(GlobalCommonException e){
        e.printStackTrace();
        return JSONResult.error(GlobalExceptionCodeEunm.PARAMETER_IS_NULL);
    }
    @ExceptionHandler(LsuExeception.class)
    public JSONResult LsuExeception(GlobalCommonException e){
        e.printStackTrace();
        return JSONResult.error(GlobalExceptionCodeEunm.LSSUE);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder builder = new StringBuilder();
        allErrors.forEach(error ->{
            builder.append(error.getDefaultMessage()+"--");
        });
        return JSONResult.error(builder.toString()+GlobalExceptionCodeEunm.PARAMETER_CHECK_FAILURE.getCode());
    }
}
